﻿using System;
using System.Windows.Forms;

namespace QuickTuner
{
    /// <summary>
    /// The play engine implementation for winforms QuickTuner client.
    /// Use the Internet Explorer control to renders the webpage
    /// </summary>
    public class IEPlayEngine : IPlayEngine
    {
        private bool _isPlaying;
        private string _currentUrl;

        private readonly WebBrowser _browser;
        private bool _hardStopped;

        public IEPlayEngine()
        {
            _isPlaying = false;
            _currentUrl = string.Empty;

            _hardStopped = false;

            _browser = new WebBrowser {
                ScriptErrorsSuppressed = true,
                CausesValidation = false,
                IsAccessible = false
                
            };
        }

        #region IPlayEngine Members

        public bool IsPlaying { get { return _isPlaying; } }

        public string CurrentUrl { get { return _currentUrl; } }

        bool IPlayEngine.SupportHardStop { get { return true; } }

        public void Play(string stationUrl)
        {
            enforceHardStop();

            _browser.Stop();

            _currentUrl = stationUrl;
            _isPlaying = true;
            _browser.Navigate(stationUrl);
        }

        public void Stop()
        {
            enforceHardStop();

            _currentUrl = string.Empty;
            _isPlaying = false;
            _browser.Stop();
        }

        public void HardStop()
        {
            _hardStopped = true;
            _browser.Dispose();
        }

        #endregion

        // if hard stop flag is set, this object is no longer operable
        private void enforceHardStop()
        {
            if (_hardStopped)
                throw new InvalidOperationException(
                    "PlayEngine has been HardStop-ed. It is no longer usable.");

        }
    }
}